<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/12
 * Time: 9:51
 */
class GenVisitNum extends ApiRedisBase
{
    public $visitRedis;
    public $expireTime;
    public $paijuLog;

    public function logic()
    {
        $this->checkUser();

        if (empty($this->params['paiZuID']) || empty($this->params['seq'])) {
            $this->returnError('empty_paiju');
        }

        $this->visitRedis = $this->redis('visit_log');
        $this->paijuLog = $this->getPaijuLog();
        $visitNum = 0;

        if ($this->paijuLog) {
            $uids = json_decode($this->paijuLog['uids'], JSON_UNESCAPED_UNICODE);
            $this->i('get_visit_num_uids', $uids);
            if ($uids) {
                //检测是否是用户的牌局
                if (!in_array($this->uid, $uids)) {
                    $this->returnError('invalid_request');
                }
                //生成有效期
                $this->geneExpireTime();
                //生成回访码
                $visitNum = $this->checkNum();
                if ($visitNum <= 0) {
                    $visitNum = $this->genNum();
                }
            }
        }

        if ($visitNum) {
            $data = array('visitNum' => (integer)$visitNum);
            $this->returnData('suc_gen_visit_num', $data);
        } else {
            $this->returnError('failed_gen_visit_num');
        }
    }

    /**
     * 获取牌局日志
     * @return array
     */
    public function getPaijuLog()
    {
        $paijuRedis = $this->redis('paiju_log');
        $key = 'PJL:' . $this->params['paiZuID'] . $this->params['seq'];
        $fields = array(
            'paiZuID',   'seq',      'time',
            'uids',      'serverID', 'roomID',
            'detail'
        );

        $result = [];
        if ($paijuRedis->exists($key)) {
            $result = $paijuRedis->hMget($key, $fields);
            $result['createTime'] = time();
        } else {
            $data = array(
                'paiZuID' => $this->params['paiZuID'],
                'seq' => $this->params['seq'],
                'fields' => $fields
            );
            $this->logWarning('no_paiju_log', $data);
        }

        return $result;
    }

    /**
     * 生成回放码
     * @return int|string
     */
    public function genNum()
    {
        $visitNum = 0;

        for ($i = 0; $i < 20; $i++) {
            $randID = mt_rand(1, 9) . sprintf('%05d', mt_rand(1, 99999));
            if (!$this->visitRedis->exists("V:" . $randID)) {
                $visitNum = $randID;
                break;
            }
        }

        if ($visitNum) {
            //保存回放码与牌局的匹配
            $paijuKey = 'PJV:' . $this->params['paiZuID'] . $this->params['seq'];
            $arr    = array('visitNum' => $visitNum);
            $result = $this->visitRedis->hMset($paijuKey, $arr);

            //保存回放码信息
            if ($result) {
                $visitKey = 'V:' . $visitNum;
                $result = $this->visitRedis->hMset($visitKey, ['uid' => $this->uid, 'createTime' => time()]);
                $this->setExpireTime($paijuKey);
                $this->setExpireTime($visitKey);
            }
            if (!$result) {
                $this->returnError('failed_save_visit_num');
            }
            //写入回访日志
            $this->writeVisitLog($visitNum);
        }

        return $visitNum;
    }

    /**
     * 拷贝牌局日志
     * @param $visitNum
     */
    public function writeVisitLog($visitNum)
    {
        if ($this->paijuLog) {
            //保存回访日志
            $key    = 'VNL:' . $visitNum;
            $result = $this->visitRedis->hMset($key, $this->paijuLog);
            if (!$result) {
                $this->logWarning('error_visit_log_save', $result);
            }

            //设置过期时间为180天
            $this->setExpireTime($key);
        }
    }

    /**
     * 检测回放码是否存在
     * @return int
     */
    public function checkNum()
    {
        $key = 'PJV:' . $this->params['paiZuID'] . $this->params['seq'];

        if ($this->visitRedis->exists($key)) {
            $result = $this->visitRedis->hMget($key, array('visitNum'));
            return $result['visitNum'];
        } else {
            $this->w('check_visit_num_error');
        }

        return 0;
    }

    /**
     * 设置过期时间
     * @param $key
     */
    public function setExpireTime($key)
    {
        $result = $this->visitRedis->expire($key, $this->expireTime);

        if (!$result) {
            $this->logWarning('failed_redis_expire', array('key' => $key));
        }
    }

    /**
     * 获取过期时间
     */
    public function geneExpireTime()
    {
        if (isset(GlobalConfig::$redis_expire['visit_log'])
            && GlobalConfig::$redis_expire['visit_log']
        ) {
            $expireDay = (integer)GlobalConfig::$redis_expire['visit_log'];
        } else {
            $expireDay = 180;
        }

        $this->expireTime = 86400 * $expireDay;
    }
}